package com.wanyang.service;

import com.wanyang.dao.MemberBrowseDao;
import com.wanyang.dos.MemberBrowseDO;
import com.wanyang.dos.MemberBrowseDOExample;
import com.wanyang.mapper.MemberBrowseDOMapper;
import com.wanyang.utils.DateUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class MemberBrowseServiceImpl implements MemberBrowseService {
    @Resource
    private MemberBrowseDOMapper memberBrowseDOMapper;

    @Resource
    private MemberBrowseDao memberBrowseDao;

    @Override
    public boolean updateTimeIfExist(Integer memberId, Integer postId) {
        MemberBrowseDOExample example = new MemberBrowseDOExample();
        example.createCriteria()
                .andMemberIdEqualTo(memberId)
                .andPostIdEqualTo(postId);

        long count = memberBrowseDOMapper.countByExample(example);
        if (count > 0) {
            MemberBrowseDO memberBrowseDO = new MemberBrowseDO();
            memberBrowseDO.setMemberId(memberId);
            memberBrowseDO.setPostId(postId);
            memberBrowseDO.setCreateTime(DateUtil.currentUnixTime());
            memberBrowseDOMapper.updateByPrimaryKeySelective(memberBrowseDO);
        }

        return count > 0;
    }

    @Override
    public boolean delEarliestRecordIfNecessary(Integer memberId) {
        MemberBrowseDOExample example = new MemberBrowseDOExample();
        example.createCriteria()
                .andMemberIdEqualTo(memberId);

        long count = memberBrowseDOMapper.countByExample(example);

        if (count > 100) {
            memberBrowseDao.delEarliestRecord(memberId, (int) count - 100);
        }

        return count > 100;
    }
}
